# a little wrapper around logcat which could be done using grep as well
# but prints in colour too.
# Displays time as well. Old messages are all displayed with the current time. 
# I should really be doing something more useful with my Saturday evenings :P
# not very efficient code either.:P
#TODO Add custom filter when you need it.
#TODO Do something about Python messing up color formatting when you break out.
#siddhu 23/10/10
import os
import sys
import time
import calendar
import re
import logging
from optparse import OptionParser

#some constants from http://stackoverflow.com/questions/287871/print-in-terminal-with-colors-using-python
#to print in different colours. I should really be using ncurses. :P
#kill this app using Ctrl+C.
#Should work on bash
HEADER = '\033[95m'
DEBUG = '\033[94m'
INFO = '\033[92m'
WARN = '\033[93m'
ERROR = '\033[91m'
ENDC = '\033[0m'

#some simple regexes to find Debug, Warning, Info, Error
DEBUG_REGEX=re.compile("^D.*$")
INFO_REGEX=re.compile("^[I,V].*$") #no extra handler for verbose
WARN_REGEX=re.compile("^W.*$")
ERROR_REGEX=re.compile("^[E,A].*$") #no extra handler for Assert


def logcatWrapper(options):
	#Logging stuff
	logger = logging.getLogger("logcat_wrapper")

	#set logging level using options given
	if options.info:
		logger.setLevel(logging.INFO)
	elif options.warn:
		logger.setLevel(level=logging.WARNING)
	elif options.error:
		logger.setLevel(level=logging.ERROR)
	else: #if none of them are set, use debug
		logger.setLevel(level=logging.DEBUG)

	consoleHandler = logging.StreamHandler()
	consoleHandler.setLevel(logging.DEBUG)
	consoleHandler.setFormatter(logging.Formatter("%(asctime)s - %(name)s - %(levelname)s: %(message)s"))	
	logger.addHandler(consoleHandler)
	#end logging stuff
	
	#filter by module. Just the same as grep
	if options.module != None:
		#TODO: replace spaces with \ ---- not important for now as ElasticDroid
		#for which it is written, is one word.
		moduleRegex = re.compile("^[A,V,D,I,W,E]/" + options.module + ".*")
	else:
		moduleRegex = None
		
	#open pipe to ADB logcat logger
	a = os.popen("adb logcat")

	#loop through the data picking out what you need
	while 1:
		line = a.readline()		
		
		currentTimeEpoch = time.time() #get the current time since epoch 1/1/70
		myTime = time.strftime("%x %X", time.localtime(currentTimeEpoch)) #get 
		#the time in the appropriate date and time format for your timezone		
		
		#strftime does not handle milliseconds. We just want two decimal pts of accuracy
		milliSec = int((currentTimeEpoch - int(currentTimeEpoch)) * 100) 
		
		#check if the line meets the module filter requirements
		if not moduleRegex or (moduleRegex and moduleRegex.match(line)):
			#print debug etc in proper colours
			if DEBUG_REGEX.match(line):
				logger.debug(DEBUG + line)
			elif INFO_REGEX.match(line):
				logger.info(INFO + line)
			elif WARN_REGEX.match(line):
				logger.warning(WARN + line)
			elif ERROR_REGEX.match(line):
				logger.error(ERROR + line)
			
		
if __name__=="__main__":
	parser = OptionParser()
	#options to set logging levels
	parser.add_option("-d", "--debug",action="store_true", help="Print\
	 debug messages and above. Default: True", default=False)
	parser.add_option("-i", "--info", action="store_true",help="Print only\
	 info messages. Default: False", default=False)
	parser.add_option("-w", "--warn", action="store_true",help="Print only\
	 warning messages. Default: False", default=False)
	parser.add_option("-e", "--error", action="store_true",help="Print only\
	 error messages. Default: False", default=False)
	#option to add module filter
	parser.add_option("-m", "--module", help = "Type the module you want to \
	see messages for.", type="string")

	(options, args) = parser.parse_args()
	
	#get the options and pass it to the logcat wrapper
	logcatWrapper(options)
